<template>
  <div class="app-container">
    <!-- 转赠管理 -->
    <el-card class="box-card mb10">
      <p v-if="giveTemp.id" style="font-size: 13px">
        <strong>更改人：</strong>{{ giveTemp.operatorName }}
      </p>

      <div class="text item">
        <el-form
          ref="dataForm"
          :rules="giveRules"
          :model="giveTemp"
          label-position="right"
          label-width="100px"
        >
          <!-- 名字 -->
          <el-form-item label="转赠管理" prop="giveFlag">
            <el-radio-group v-model="giveTemp.giveFlag" class="mr10">
              <el-radio label="0">不可转赠</el-radio>
              <el-radio label="1">转赠期</el-radio>
            </el-radio-group>
            <el-input-number
              v-if="giveTemp.giveFlag == 1"
              v-model="giveTemp.giveDays"
              :min="0"
              label="转赠时长"
            />
          </el-form-item>

          <!-- 按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              :disabled="giveTemp.giveFlag == null"
              @click="handleGiveSave"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 寄售管理 -->
    <el-card class="box-card mb10">
      <p v-if="saleTemp.id" style="font-size: 13px">
        <strong>更改人：</strong>{{ saleTemp.operatorName }}
      </p>

      <div class="text item">
        <el-form
          ref="saleForm"
          :rules="saleRules"
          :model="saleTemp"
          label-position="right"
          label-width="120px"
        >
          <!-- 名字 -->
          <el-form-item label="寄售管理" prop="saleFlag">
            <el-radio-group v-model="saleTemp.saleFlag" class="mr10">
              <el-radio label="0">不可寄售</el-radio>
              <el-radio label="1">寄售期</el-radio>
            </el-radio-group>
            <el-input-number
              v-if="saleTemp.saleFlag == 1"
              v-model="saleTemp.saleDays"
              :min="0"
              label="寄售时长"
            />
          </el-form-item>
          <el-form-item label="基础费率(%)" prop="saleBasicRate" required>
            <el-input-number v-model="saleTemp.saleBasicRate" :min="0" label="基础费率" />
            <div class="hint">包含：版权费（2.5%） + 综合服务费 + 提现服务费（1%）</div>
          </el-form-item>

          <!-- 按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              :disabled="saleTemp.saleFlag == null"
              @click="handleSaleSave"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 活动费率 -->
    <el-card class="box-card mb10">
      <p style="font-size: 13px">
        <strong>活动费率：</strong>
      </p>
      <p class="hint" style="font-size: 13px">
        包含：版权费（2.5%） + 综合服务费 + 提现服务费（1%）
      </p>
      <el-button class="mb10" size="mini" type="success" @click="handleAdd">
        添加
      </el-button>
      <!-- 表格 -->
      <el-table
        v-loading="listLoading"
        :data="tableData"
        border
        fit
        highlight-current-row
        size="mini"
      >
        <el-table-column label="#" type="index" width="50" />
        <el-table-column label="条件">
          <template slot-scope="{ row }">
            <div>{{ row.worksName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="活动费率(%)" prop="saleRate" />
        <el-table-column label="开始时间" prop="startTime" />
        <el-table-column label="结束时间" prop="endTime" />
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="操作人" prop="operatorName" />
        <el-table-column label="操作" width="150">
          <template slot-scope="{ row }">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="m-center">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="fetchList"
        />
      </div>
    </el-card>

    <!-- 提现设置 -->
    <el-card class="box-card mb10">
      <p style="font-size: 13px">
        <strong>提现设置：</strong>
      </p>

      <div class="text item">
        <el-form
          ref="cashForm"
          :model="cashTemp"
          label-position="right"
          label-width="110px"
        >
          <!-- 提现额度 -->
          <el-form-item label="提现额度" required>
            <el-input-number v-model="cashTemp.min" label="最低限额" />
            <span class="ml10 mr10">~</span>
            <el-input-number v-model="cashTemp.max" label="最高限额" />
          </el-form-item>

          <!-- 最高限额 -->
          <el-form-item label="一天提现次数" prop="day" required>
            <el-input-number v-model="cashTemp.day" label="基础费率" />
          </el-form-item>

          <!-- 按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleCashSave">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 官方交流群 -->
    <el-card class="box-card">
      <div class="text item">
        <el-form
          :rules="codeRules"
          :model="codeTemp"
          label-position="right"
          label-width="95px"
        >
          <el-form-item label="官方交流群" prop="officialCode" required>
            <el-upload
              :headers="$store.getters.uploadHeaders"
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="codeTemp.officialCode"
                :src="getFile(codeTemp.officialCode)"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
              <div slot="tip" class="el-upload__tip">
                支持png、jpeg、jpg、gif图片格式, 不能超过 200KB!
              </div>
            </el-upload>
          </el-form-item>
          <!-- 按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              :disabled="!codeTemp.officialCode"
              @click="handleCodeSave"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 编辑 -->
    <el-dialog title="新增" :visible.sync="dialogVisible" width="600px">
      <el-form
        ref="tempDataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="110px"
      >
        <el-form-item label="拥有藏品" required>
          <el-tooltip
            class="item"
            effect="dark"
            content="添加以后，不能更改"
            placement="top"
          >
            <el-select
              v-model="temp.worksId"
              placeholder="输入拥有的藏品"
              remote
              filterable
              clearable
              :remote-method="remoteGetSoldWorks"
              class="mr10"
            >
              <el-option
                v-for="item in soldWorksOptions"
                :key="item.id"
                :label="item.worksName"
                :value="item.id"
              />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="活动费率(%)" prop="saleRate" required>
          <el-input-number v-model="temp.saleRate" :min="0" label="基础费率" />
        </el-form-item>
        <!-- <el-form-item label="开始时间" prop="startTime" required>
          <el-date-picker
            v-model="temp.startTime"
            type="datetime"
            placeholder="开始时间"
            :picker-options="pickerOptions"
          />
        </el-form-item> -->
        <el-form-item label="时间范围" prop="datetimerange" required>
          <el-date-picker
            v-model="temp.datetimerange"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="结束时间" prop="endTime" required>
          <el-date-picker
            v-model="temp.endTime"
            type="datetime"
            placeholder="结束时间"
            :picker-options="pickerOptions"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="add()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getFile, beforeAvatarUpload, uploadUrl } from "@/utils";
import { findWorks } from "@/api/condition";
import { queryGive, saveGiveSet } from "@/api/give";
import { querySale, saveSaleSet, fetchList, add, remove } from "@/api/secondhandSale";
import { queryCode, saveCode } from "@/api/code";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const defaultForm = {
  worksId: null,
  saleRate: 1,
  endTime: null,
  startTime: null,
  datetimerange: null,
};

const giveDefaultForm = {
  id: null,
  giveFlag: null,
  giveDays: null,
};

const saleDefaultForm = {
  saleBasicRate: 10,
  saleFlag: null,
  saleDays: null,
};

const cashDefaultForm = {
  day: null,
  min: null,
  max: null,
};

export default {
  components: { Pagination },
  data() {
    return {
      // 转赠管理
      giveTemp: Object.assign({}, giveDefaultForm),
      giveRules: {
        giveFlag: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      // 寄售管理
      saleTemp: Object.assign({}, saleDefaultForm),
      saleRules: {
        saleFlag: [{ required: true, message: "请选择", trigger: "blur" }],
      },

      // 提现管理
      cashTemp: Object.assign({}, cashDefaultForm),

      // 活动费率列表
      listLoading: false,
      tableData: [],
      total: 0,
      listQuery: {
        limit: 10,
        page: 1,
      },
      dialogVisible: false,
      temp: Object.assign({}, defaultForm),
      rules: {
        saleRate: [{ required: true, message: "请输入活动费率", trigger: "blur" }],
        // startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        // endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
        datetimerange: [{ required: true, message: "请选择时间范围", trigger: "blur" }],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      // 官方交流群
      uploadUrl,
      codeTemp: { officialCode: "" },
      codeRules: {
        officialCode: [{ required: true, message: "请上传二维码", trigger: "blur" }],
      },
      soldWorksOptions: [],
    };
  },
  created() {
    this.queryGive();
    this.querySale();
    this.fetchList();
    this.queryCash();
    this.queryCode();
  },
  methods: {
    // 转赠管理
    queryGive() {
      queryGive().then((res) => {
        if (res.id) {
          this.giveTemp = res;
        }
      });
    },
    handleGiveSave() {
      this.$confirm(`你确定要更改设置吗?`, "提示", {
        type: "warning",
      })
        .then(() => {
          this.saveGiveSet();
        })
        .catch(() => {
          this.$message.info("已取消更改");
        });
    },
    saveGiveSet() {
      saveGiveSet(this.giveTemp).then(() => {
        this.$message.success("更改成功");
        this.queryGive();
      });
    },

    // 寄售管理
    querySale() {
      querySale().then((res) => {
        if (res.id) {
          this.saleTemp = res;
        }
      });
    },
    handleSaleSave() {
      this.$confirm(`你确定要更改设置吗?`, "提示", {
        type: "warning",
      })
        .then(() => {
          this.saveSaleSet();
        })
        .catch(() => {
          this.$message.info("已取消更改");
        });
    },
    saveSaleSet() {
      saveSaleSet(this.saleTemp).then(() => {
        this.$message.success("更改成功");
        this.querySale();
      });
    },

    // 提现管理
    queryCash() {
      console.log("queryCashqueryCash");
      queryCashSet().then((res) => {
        this.cashTemp = res;
      });
    },

    // 查询已售作品
    remoteGetSoldWorks(query) {
      if (query !== "") {
        setTimeout(() => {
          findWorks({
            worksName: query,
          }).then((res) => {
            this.soldWorksOptions = res;
          });
        }, 200);
      } else {
        this.soldWorksOptions = [];
      }
    },
    // 得到列表
    async fetchList() {
      this.listLoading = true;
      fetchList(this.listQuery).then((response) => {
        this.tableData = response.data.items;
        this.total = response.total;
        this.listLoading = false;
      });
    },
    // 重置数据
    resetTemp() {
      this.temp = Object.assign({}, defaultForm);
    },
    // 点击“添加”按钮
    handleAdd() {
      this.resetTemp();
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["tempDataForm"].clearValidate();
      });
    },
    // 添加
    add() {
      this.$refs["tempDataForm"].validate((valid) => {
        if (valid) {
          this.temp.startTime = this.temp.datetimerange[0];
          this.temp.endTime = this.temp.datetimerange[1];
          add(this.temp).then((response) => {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.fetchList();
          });
        }
      });
    },

    // 删除
    handleDelete(row) {
      this.$confirm(`你确定要删除吗?`, "提示", {
        type: "warning",
      })
        .then(() => {
          remove({ id: row.id }).then(() => {
            this.$message.success("删除成功");
            this.dialogVisible = false;
            this.fetchList();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    /*  文件相关--start */
    // 上传之前
    beforeAvatarUpload,
    // 上传成功
    handleAvatarSuccess(res, file) {
      const url = res.data.url;
      this.codeTemp.officialCode = url;
    },
    getFile,
    queryCode() {
      queryCode().then((res) => {
        if (res.id) {
          this.codeTemp = res;
        }
      });
    },
    handleCodeSave() {
      this.$confirm(`你确定要更改吗?`, "提示", {
        type: "warning",
      })
        .then(() => {
          this.saveCode();
        })
        .catch(() => {
          this.$message.info("已取消更改");
        });
    },
    saveCode() {
      saveCode(this.codeTemp).then(() => {
        this.$message.success("更改成功");
        this.queryCode();
      });
    },
    /*  文件相关--end */
  },
};
</script>
